// pages/search/search.ts
const searchHttpService = require('../../utils/beans');
Page({
  //清除历史记录
  cleanhistory: function (e) {
    this.setData({
      history: false, //隐藏历史记录
      historyArray: [], //清空历史记录数组
      newArray: [],
      shoopingtext: "" //清空搜索框
    })
  },
  //搜索
  search: function (e) {
    var searchtext = this.data.shoopingtext; //搜索框的值
    var sss = true;
    if (searchtext != "") {
      //将搜索框的值赋给历史数组
      this.data.historyArray.push(searchtext);
      this.getSearchList(searchtext);
      this.setData({
        history: false, //隐藏历史记录
        // noneview: true, //隐藏未找到提示
        // shoppinglist: true, //显示病害列表
        newArray: this.data.historyArray //给新历史记录数组赋值
      })
    } else {
      this.setData({
        noneview: true, //显示未找到提示
        shoppinglist: false, //隐藏商品列表
        history: false, //隐藏历史记录
      })
    }
  },
  data: {
    shoopingtext: "", //搜索框的值
    history: false, //显示历史记录
    noneview: false, //显示未找到提示
    shoppinglist: false, //显示病害列表
    historyArray: [], //历史记录数组,
    newArray: [], //添加历史记录数组
    shoppingArray: [], // 改为 shoppinglist 接收接口数据
    pageNo: 1,
    pageSize: 5
  },
  //搜索框的值
  shoppinginput: function (e) {
    //当删除input的值为空时
    if (e.detail.value == "") {
      this.setData({
        history: true, //显示历史记录
        shoppinglist: false //隐藏商品列表
      });
      //所有商品列表的状态改为0
      for (var index in this.data.shoopingarray) {
        let temp = 'shoopingarray[' + index + '].status';
        this.setData({
          [temp]: 0,
        })
      }
    }
    this.setData({
      shoopingtext: e.detail.value
    })
  },
  //点击历史记录赋值给搜索框
  textfz: function (e) {
    this.setData({
      shoopingtext: e.target.dataset.text
    })
  },
  onLoad() {
    this.setData({
      history: true, //显示历史记录
      noneview: true, //显示未找到提示
    })
  },
  getSearchList(requestData: string) {
    if (!requestData) {
      console.error('"请求信息为空"');
      return;
    }
    const url = `selectPest/selectPestByKeyword/?keyword=${encodeURIComponent(requestData)}`;
    searchHttpService.get(url)
      .then((response) => {
        console.log(response)
        if (response.total != 0) {
          this.setData({
            shoppingArray: response.list,
            noneview: false,
            shoppinglist: true, //显示病害列表
          })
        } else {
          this.setData({
            noneview: true,
            shoppinglist: false, //隐藏商品列表
            history: false, //隐藏历史记录
          })
        }
      })
  },

  // 点击跳转详情页
  goToDetail(e) {
    const pid = e.currentTarget.dataset.pid;
    wx.navigateTo({
      url: `/pages/detail/detail?pid=${pid}`
    });
  }
})